import jwt from "jsonwebtoken";
import { COOKIE_KEY } from "../utils/generateToken.js";
import User from "../models/user.model.js";

const protectRoute = async (req, res, next) => {
  try {
    const token = req.cookies[COOKIE_KEY];
    // console.log(`tokin ${token}`);
    if (!token) {
      res.status(401).json({ error: "Unauthorized - No Token Provided" });
      return;
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    if (!decoded) {
      res.status(401).json({ error: "Unauthorized - Invalid Token" });
      return;
    }
    const user = await User.findById(decoded.userId).select("-password");
    if (!user) {
      res.status(404).json({ error: "User not found" });
      return;
    }

    // 为请求对象添加参数 user
    req.user = user;

    next();
  } catch (err) {
    console.error("Error in protectRoute middleware: ", err.message);
    res.status(500).json({ error: "Internal server error" });
  }
};

export default protectRoute;
